const { OPTION_IS_NOT_ALLOW } = require("../config/error")
const permissionService = require("../service/permission.service")

const verifPermission = async (ctx, next) => {
    // 1.获取修改动态、登陆用户的id
    // const { momentId } = ctx.params
    const { id } = ctx.user
    // console.log(momentId, id)


    /* 
        name => moment/user/comment/label
        params => { momentId: 4}
        keyName => momentId
    */
    const keyName = Object.keys(ctx.params)[0] //momentId
    const resourceId = ctx.params[keyName] //4
    const resourceName = keyName.replace('Id', '') //moment
    // 2.查询userid是否有momentid的权限
    const isPermission = await permissionService.checkResource(resourceName, resourceId, id)

    console.log(isPermission)
    if (!isPermission) {
        return ctx.app.emit('error', OPTION_IS_NOT_ALLOW, ctx)
    }
    // 3.执行下一个中间件
    await next()

}
module.exports = { verifPermission }